import axios from 'axios';

/** 请求类 */
class Request {
  #instance;

  constructor(baseConfig) {
    this.#instance = axios.create(baseConfig);
    const interceptorsObj = baseConfig.interceptors;

    this.#instance.interceptors.request.use(
      interceptorsObj.requestInterceptor,
      interceptorsObj.requestInterceptorCatch,
    );

    this.#instance.interceptors.response.use(
      interceptorsObj.responseInterceptor,
      interceptorsObj.responseInterceptorCatch,
    );
  }

  /** 请求方法 添加错误处理 */
  async request(config) {
    try {
      const res = await this.#instance.request(config);
      return res;
    } catch (error) {
      return {
        code: 0,
        errorCode: '',
        errorDesc: '',
        data: null,
        msg: '网络错误',
        error,
      };
    }
  }
}

/** 暂时只添加get、post请求 */
export const request = (baseConfig) => {
  const api = new Request(baseConfig);
  return {
    get: (url, params, config) => api
      .request({
        method: 'GET',
        url,
        params,
        ...config,
      }),
    post: (url, data, config) => api
      .request({
        method: 'POST',
        url,
        data,
        ...config,
      }),
  };
};
